import { Controller, Get, Post, Body, Patch, Param, Delete, Res } from '@nestjs/common';
import { RxjsTestService } from './rxjs-test.service';
import { Observable } from 'rxjs';
import { take } from 'rxjs/operators';
import type { Response } from 'express';
@Controller('rxjs-test')
export class RxjsTestController {
  constructor(private readonly rxjsTestService: RxjsTestService) { }

  @Get('data')
  getData(): Observable<number[]> {
    return this.rxjsTestService.getData();
  }

  @Get('interval2')
  getInterval2(): Observable<number> {
    return this.rxjsTestService.getIntervalData()
  }

  @Get('interval')
  getIntervalData(@Res() res: Response): void {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    const observable: Observable<number> = this.rxjsTestService.getIntervalData();
    // take控制输出次数
    const subscription = observable.pipe(take(10)).subscribe((value) => {
      res.write(`data: ${value}\n\n`);
    }, (error) => {
      res.write(`data: ${error}\n\n`);
    }, () => {
      res.end();
    });

    // Handle client disconnection
    res.on('close', () => {
      subscription.unsubscribe();
    });
  }


}
